package test17.syn;

public class SellTicket {
    public static void main(String[] args) {
        SellTicket01 sellTicket01 = new SellTicket01();
        sellTicket01.start();
        SellTicket01 sellTicket011 = new SellTicket01();
        sellTicket011.start();
        SellTicket01 sellTicket012 = new SellTicket01();
        sellTicket012.start();
    }
}

//使用Thread继承方法实现
//使用 Thread 实现代码块的时候需要注意，因为 Thread 创建线程每个线程都会创建一个新对象，所以使用 Thread 方式实现同步的时候要注意锁的对象
class SellTicket01 extends Thread {
    private static int ticketNum = 100;//让多个线程共享 ticketNum
    private static boolean loop = true;
    private static Object object = new Object();

    @Override
    public void run() {
        while (loop) {
            sell();
        }
    }

    public static void sell() {
        synchronized (SellTicket01.class) {
            if (ticketNum <= 0) {
                System.out.println("售票结束...");
                loop = false;
                return;
            }
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("窗口 " + Thread.currentThread().getName() + " 售出一张票"
                    + " 剩余票数=" + (--ticketNum));
        }
    }
}


//实现接口方式，使用synchronized实现线程同步
class SellTicket04 implements Runnable {
    private int ticketNum = 100;
    private boolean loop = true;
    Object object = new Object();

    @Override
    public void run() {
        while (loop) {
            sell02();
        }
    }


    //同步代码块非静态
    public void sell02() {
        synchronized (object/*或者是this*/) {
            if (ticketNum <= 0) {
                System.out.println("售票结束...");
                loop = false;
                return;
            }
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("窗口 " + Thread.currentThread().getName() + " 售出一张票"
                    + " 剩余票数=" + (--ticketNum));
        }
    }

    //同步代码块静态
    public static void m2() {
        synchronized (SellTicket04.class) {
            System.out.println("m2");
        }
    }


    //同步方法非静态
    public synchronized void sell() {
        if (ticketNum <= 0) {
            System.out.println("售票结束...");
            loop = false;
            return;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("窗口 " + Thread.currentThread().getName() + " 售出一张票"
                + " 剩余票数=" + (--ticketNum));
    }

    //同步方法静态的
    public synchronized static void m1() {
    }
}